<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Login extends Controller
{
    public function index(Request $request) {

        if ($request->isMethod('post')) {
            if (!captcha_check($request->input('captcha'))) {
                return response()->json(['status'=>'fail', 'msg'=>'验证码错误']);
            }

            $admin = $request->only(['username', 'password']);
            
            //数据库查询
            $res = DB::table('admin')->where('username', $admin['username'])->first();

            if (!$res) {
                return response()->json(['status'=>'fail', 'msg'=>'用户名不存在']);
            }

            if ($res->password == md5($admin['password'])) {
                // 存入SESSION
                session(['username' => $admin['username']]);
                // 登录成功
                return response()->json(['status'=>'success', 'msg'=>'登录成功']);
            } else {
                return response()->json(['status'=>'fail', 'msg'=>'密码错误']);
            }
        } else {
            return view('login.index');
        }
    }

    public function logout() {
        session(['username'=>null]);
        return response()->json(['status'=>'success', 'msg'=>'退出登录']);
    }
}
